﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Data.SqlClient;
using System.Data;

namespace FrbaCommerce.Codigo_reutilizable
{
    class PasswordHash
    {
        public string SHA256Encrypt(string input)
        {
            SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider();

            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashedBytes = provider.ComputeHash(inputBytes);

            StringBuilder output = new StringBuilder();

            for (int i = 0; i < hashedBytes.Length; i++)
                output.Append(hashedBytes[i].ToString("x2").ToLower());

            return output.ToString();
        }


        public string getDbPasswd(int usuario)
        {
            string sql = "SELECT usr_passwd FROM Monkey_Coders.Usuarios WHERE usuario_id = " + Convert.ToInt32(usuario);
            return getDbPasswdUnificado(sql);
        }

        public string getDbPasswd(string usuario)
        {
            string sql = "SELECT usr_passwd FROM Monkey_Coders.Usuarios WHERE usr_name= '" + usuario + "'";
            return getDbPasswdUnificado(sql);
        }

        private string getDbPasswdUnificado(string sql)
        {
            string passDB = "";

            using (SqlConnection conn = Program.obtenerConexion())
            {
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    passDB = (string)cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    // cerramos la conexion
                    if (conn.State != ConnectionState.Closed)
                        conn.Close();
                    // destruimos la conexion
                    conn.Dispose();
                }
            }
            return passDB;
        }

        private string convertirBytesAstring(byte[] array)
        {
            int i;
            string cadena = "";
            for (i = 0; i < array.Length; i++)
            {
                cadena += String.Format("{0:x2}", array[i]);
            }
            return cadena;
        }

        public string getHashedPasswd(string password)
        {
            string passwd = "";


            SHA256 mySHA256 = SHA256Managed.Create();
            byte[] hashValue;

            hashValue = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(password));

            for (int i = 0; i < hashValue.Length; i++)
            {
                passwd += String.Format("{0:x2}", hashValue[i]);
            }

            return passwd;
        }

    }
}
